package com.nidu.demo.post.ability;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.post.gateway.PositionGateway;
import com.nidu.demo.post.model.Position;
import com.nidu.demo.user.gateway.UserPositionGateway;
import com.nidu.demo.user.model.UserPosition;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Set;
import java.util.Map;
import java.util.List;

@Component
@RequiredArgsConstructor
public class PositionDomainService {

    private final PositionGateway gateway;

    private final UserPositionGateway userPositionGateway;

    /**
     * 检查对象是否已存在
     * @param code
     * @param companyId
     * @param excludeId
     */
    public void validateDuplicate(String code, Long companyId, Long excludeId) {
        Position post = gateway.getByCodeAndCompanyId(code, companyId);
        if (post != null) {
            if(excludeId == null){
                throw new BizException(ErrorCodeConstants.POSITION_CODE_DUPLICATE.getCode(),
                        ErrorCodeConstants.POSITION_CODE_DUPLICATE.getMessage());
            } else if(excludeId.equals(post.getId())) {
                throw new BizException(ErrorCodeConstants.POSITION_CODE_DUPLICATE.getCode(),
                        ErrorCodeConstants.POSITION_CODE_DUPLICATE.getMessage());
            }
        }
    }

    public List<Position> validatePositionList(Set<Long> postIds) {
        if(!CollUtil.isEmpty(postIds)){
            List<Position> posts = gateway.getByIds(postIds);
           if(postIds.size() != posts.size()){
               throw new BizException(ErrorCodeConstants.POSITION_NOT_FOUND.getCode(),
                       ErrorCodeConstants.POSITION_NOT_FOUND.getMessage());
           }
            return posts;
        }
        return null;
    }

    public void deletePosition(Long postId) {
        // 1. 是否被角色绑定
        validateUserUse(Collections.singleton(postId));

        // 2. 执行逻辑删除
        userPositionGateway.removePostUsers(postId);
        gateway.deleteById(postId);
    }

    public void deletePositions(Set<Long> postIds) {
        // 1. 是否被角色绑定
        validateUserUse(postIds);

        // 2. 执行逻辑删除
        userPositionGateway.removePostsUsers(postIds);
        gateway.deleteByIds(postIds);
    }

    /**
     * 检查职位是否被用户使用
     * @param postIds
     */
    private void validateUserUse(Set<Long> postIds) {
        Map<Long, List<UserPosition>> userDepartmentMap = userPositionGateway.getByPostIds(postIds);
        if (!CollUtil.isEmpty(userDepartmentMap)) {
            throw new BizException(ErrorCodeConstants.POSITION_HAS_USER.getCode(),
                    ErrorCodeConstants.POSITION_HAS_USER.getMessage());
        }
    }
}